package wei.zhang.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * 精确查询 分表
 */
public class RreciseTableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {


    /**
     * 用于 等于或者in() 具体的值的时候，使用
     * @param collection  拿到所有符合逻辑表的
     * @param preciseShardingValue
     * @return
     */
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {

        //逻辑表
        String logicTableName = preciseShardingValue.getLogicTableName();
        //分表字段
        String id = preciseShardingValue.getColumnName();
        // 分表字段值
        Long value = preciseShardingValue.getValue();

        BigInteger bigInteger = BigInteger.valueOf(value);
        // value%2 +1;
        BigInteger result = (bigInteger.mod(new BigInteger("2"))).add(new BigInteger("1"));
        String key = logicTableName+"_"+ result;
        if (collection.contains(key)) {
            return key;
        }
        throw new UnsupportedOperationException("table route " + key + " is not support please check your config");
    }
}
